﻿using BootstrapBlazor.Components;
using SqlSugar;

namespace HelloApp.Server.Data
{

    public class CustomDataService<Titem> : DataServiceBase<Titem> where Titem : class,new()
    {
        static SqlSugarClient db_client =>  new SqlSugarClient(new ConnectionConfig()
        {
            ConnectionString = $"datasource = {Path.Combine(even?.WebRootPath??"", "demo.db")}",
            DbType = DbType.Sqlite,
            IsAutoCloseConnection = true
        }, db => { });

        static IWebHostEnvironment? even;

        public string ErrorInfo { get; set; } = string.Empty;

        public CustomDataService(IWebHostEnvironment _even)
        {
            even = _even;
            var c = db_client;

            c.DbMaintenance.CreateDatabase();

            c.CodeFirst.InitTables<Material>();
            c.CodeFirst.InitTables<MattressConfig>();
        }

        public override async Task<QueryData<Titem>> QueryAsync(QueryPageOptions option)
        {
            var items = await db_client.Queryable<Titem>().ToListAsync();
            var total = items.Count();

            return new QueryData<Titem>() {
                Items = items,
                TotalCount = total
            };
        }

        public override Task<bool> AddAsync(Titem model)
        {
            return Task.FromResult(true);
        }

        public override async Task<bool> DeleteAsync(IEnumerable<Titem> models)
        {
            return await db_client.Deleteable(models.ToList()).ExecuteCommandHasChangeAsync();
        }

        public override async Task<bool> SaveAsync(Titem model, ItemChangedType changedType)
        {
            try
            {
                if (changedType == ItemChangedType.Update)
                {
                    try
                    {
                        return await db_client.Updateable(model).ExecuteCommandHasChangeAsync();
                    }catch(Exception ex)
                    {
                        ErrorInfo = ex.ToString();
                    }
                }
                else if(changedType == ItemChangedType.Add)
                {
                    try
                    {
                        return await db_client.Insertable(model).ExecuteCommandAsync() > 0;
                    }
                    catch (Exception ex)
                    {
                        ErrorInfo = ex.ToString();
                    }
                    
                }
            }
            catch(Exception ex)
            {
                System.Console.WriteLine($"Error: {ex}");
            }

            return false;
        }

        public async Task<MattressConfig> GetConfig()
        {
            var z = await db_client.Queryable<MattressConfig>().FirstAsync();
            if(z is not null)
            {
                return z;
            }
            else
            {
                return new MattressConfig();
            }
        }

        public async Task<bool> SaveConfig(MattressConfig config)
        {
            try
            {
                return await db_client.Updateable<MattressConfig>(config).ExecuteCommandHasChangeAsync();
            }
            catch (Exception ex)
            {
                ErrorInfo = ex.ToString();
            }
            return false;
        }

    }
    
}
